<?php namespace App\Services\Admin;

use App\Facades\Infra\Admin\UserManage;
use App\Facades\Utils\ValidateParameter;
use App\Facades\Utils\LogUtil;
use Auth;

class UserService{
	public function getUsers(){
		return UserManage::getUsers();
	}

	public function getRoles(){
		return UserManage::getRoles();
	}

	public function create($request){

		$rules = [
			'uname' => 'required|unique:users,uname',
			'name' => 'required',
			'password' => 'required',
			'role_id' => 'required|exists:roles,id'
		];

		ValidateParameter::validate($request,$rules);

		$data = $request->all();

		UserManage::createUser($data);

		LogUtil::createLog(Auth::user()->name,'创建了一个新用户：'.$data['name']);
	}

	public function delete($request){

		$rules = [
			'id' => 'required|exists:users,id'
		];

		ValidateParameter::validate($request,$rules);

		$data = $request->all();

		$user = UserManage::deleteUser($data);

		LogUtil::deleteLog(Auth::user()->name,'删除了一个用户：'.$user->name);
	}

	public function updatePassword($request){

		$rules = [
			'new_password' => 'required',
			'confirm_password' => 'required|same:new_password'
		];

		ValidateParameter::validate($request,$rules);

		$data = $request->all();

		$id = Auth::user()->id;

		$info = [
			'password' => bcrypt($data['new_password'])
		];

		UserManage::updatePassword($id,$info);

		LogUtil::updateLog(Auth::user()->name,'修改了登陆密码');


	}

	public function update($request){

		$data = $request->all();

		$rules = [
			'id' => 'required|exists:users,id',
			'uname' => 'required|unique:users,uname,'.$data['id'],
			'name' => 'required',
			'role_id' => 'required|exists:roles,id'
		];

		ValidateParameter::validate($request,$rules);

		$id = $data['id'];

		$info = [
			'uname' => $data['uname'],
			'name' => $data['name'],
			'role_id' => $data['role_id']
		];

		$user = UserManage::updateUserInfo($id,$info);

		// dd(Auth::user());

		LogUtil::updateLog(Auth::user()->name,'修改了用户信息:'.$user->name);
	}
}